package com.lz.ccjdemo.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lz.ccjdemo.R;
import com.lz.ccjdemo.utils.file.FileHttpManager;
import com.lz.ccjdemo.utils.file.callback.IProgressListener;
import com.lz.ccjdemo.utils.file.down.DownUtils;
import com.lz.ccjdemo.utils.listener.PerfectClickListener;

import java.io.File;
import java.math.BigDecimal;

/**
 * 更新版本管理
 */
public class UpdateAppUtils {
    private final String TAG_APK_PATH = Environment.getExternalStorageDirectory() + "/Download/apk/";//安装包要保存的位置
    private DownUtils downUtils;
    private static UpdateAppUtils instance;
    private AlertDialog dialog;

    private UpdateAppUtils() {

    }

    public static UpdateAppUtils getInstance() {
        if (instance == null) {
            instance = new UpdateAppUtils();
        }
        return instance;
    }

    public AlertDialog showAppUpdateDialog(Context context, String version, String title, boolean isShowCancel, DialogClickListener dialogClickListener) {
        dialog = new AlertDialog.Builder(context, R.style.dialog).setCancelable(false).create();
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_app_update, null);
        TextView tvTitle = dialogView.findViewById(R.id.tv_content);
        ImageView tvCancel = dialogView.findViewById(R.id.btn_cancel);
        TextView tvConfirm = dialogView.findViewById(R.id.btn_update);
        TextView tvVersion = dialogView.findViewById(R.id.tv_version);
        tvVersion.setText(version);
        tvTitle.setText(title);
        if (isShowCancel) {
            tvCancel.setVisibility(View.VISIBLE);
        } else {
            tvCancel.setVisibility(View.GONE);
        }
        tvCancel.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                //取消更新
                if (dialogClickListener != null) {
                    dialogClickListener.onCancel(dialog);
                }
            }
        });
        tvConfirm.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                //开始更新
                if (dialogClickListener != null) {
                    dialogClickListener.onConfirm(dialog);
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface d) {
                //dialog消失
                if (dialogClickListener != null) {
                    dialogClickListener.onDismiss();
                }
            }
        });
        dialog.setView(dialogView);
        dialog.show();

        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = LinearLayout.LayoutParams.MATCH_PARENT;//宽高设置具体大小
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(lp);
        return dialog;
    }


    public void updateApp(Activity context, PermissionsUtils permissionsUtils, boolean isCancel, String appUrl) {
        permissionsUtils.requestPermissions(context,new PermissionsUtils.OnResultListener() {
            @Override
            public void accept(boolean isSuccess) {
                if (isSuccess) {
                    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, context.getComponentName().getClassName());
                    wakeLock.acquire(10*60*1000L /*10 minutes*/);
                    TextView tvText = dialog.findViewById(R.id.btn_update);
                    ImageView tvCancel = dialog.findViewById(R.id.btn_cancel);
                    tvText.setEnabled(false);
                    if (isCancel) {
                        tvCancel.setVisibility(View.INVISIBLE);
                    }
                    downUtils = FileHttpManager.down(
                                    appUrl,
                                    TAG_APK_PATH, "name.apk")
                            .registerProgressListener(new IProgressListener() {
                                @Override
                                public void onSuccess(String path) {
                                    if (tvText != null) {
                                        tvText.setText("立即安装");
                                        tvText.setEnabled(true);
                                        if (isCancel) {
                                            tvCancel.setVisibility(View.VISIBLE);
                                        }
                                    }
                                    Tools.installApk(context, new File(path));
                                    wakeLock.release();
                                }

                                @Override
                                public void onProgress(long progress, long totalProgress) {
                                    BigDecimal bd = BigDecimal.valueOf(((float) progress / (float) totalProgress) * 100);
                                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    if (tvText != null) {
                                        tvText.setText(bd + "%");
                                    }
                                }

                                @Override
                                public void onError(Exception error) {
                                    if (tvText != null) {
                                        tvText.setText("下载失败");
                                        tvText.setEnabled(true);
                                        if (isCancel) {
                                            tvCancel.setVisibility(View.VISIBLE);
                                        }
                                    }
                                    wakeLock.release();
                                }

                            });
                    downUtils.startDown(0);
                } else {
                    Toast.makeText(context, "权限获取失败", Toast.LENGTH_SHORT).show();
                }
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    public interface DialogClickListener {
        void onCancel(Dialog dialog);

        void onConfirm(Dialog dialog);

        void onDismiss();
    }
}
